package com.easy.easybook.controller;

import com.easy.easybook.dao.CategoryMapper;
import com.easy.easybook.entity.Books;
import com.easy.easybook.entity.Category;
import com.easy.easybook.service.CategoryService;
import com.easy.easybook.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author http://zouyujie.top
 * @date 2021/12/19 14:36
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryMapper categoryMapper;
    @ResponseBody
    @GetMapping("/list")
    public R selectAll(){
        List<Category> categories = categoryService.selectAll();
        return R.ok().put("data", categories);
    }
    @ResponseBody
    @PostMapping("/add")
    public R add(@RequestBody Category category){
        categoryService.save(category);
        return R.ok();
    }
    @ResponseBody
    @PostMapping("/update")
    public R update(@RequestBody Category category){
        categoryService.update(category, category.getId());
        return R.ok();
    }
    @ResponseBody
    @PostMapping("/delete")
    public R delete(@RequestBody Category category){
        List<Books> books = categoryMapper.selectSome(category.getId());
        if(!books.isEmpty()){
           return R.error(9000, "请先删除对应的图书依赖");
        }
        categoryService.delete(category.getId());
        return R.ok();
    }

    @ResponseBody
    @PostMapping("/search")
    public R search(@RequestBody Category category){
        if("".equals(category.getName())){
            List<Category> categories = categoryMapper.listAll();
            return R.ok().put("data", categories);
        }
        List<Category> categories = categoryMapper.selectCategory(category.getName());
        return R.ok().put("data", categories);
    }
}
